from ctypes import *
from ctypes.util import find_library
from magicktypes import filterTypes, boolean
libname =  find_library("Wand")
magic = cdll.LoadLibrary(libname)
magic.MagickWandGenesis()
import atexit

def closeWand():
    magic.MagickWandTerminus()
    return 0

atexit.register(closeWand)


"""
MagicWand is a ImageMagick library wrapper for python.
MagicWand is about simplicity. Most frequent tasks are easy to accomplish.
"""

class Image:
    def __init__(self, filename):
        self.filename = filename
        self.wand = None

    def setWand(self, wand):
        self.wand = wand
    
    def write(self, filename):
        if self.wand == None:
            print "ping!"
        magic.MagickWriteImages(self.wand, filename, boolean.True)




class Wand:
    def __init__(self):
        self.wand = magic.NewMagickWand()

    def resize(self, width, height, filterType=None):
        if filterType == None:
            filterType = filterTypes.LanczosFilter
        for i in self._iterate():
            magic.MagickResizeImage(self.wand, width, height,
                                    filterType, 1)

    def add(self, image):
        if isinstance(image, Image):
            image.setWand(self.wand)
        magic.MagickReadImage(self.wand, image.filename)
        
    def contrast(self, sharpen):
        magic.MagickContrastImage(self.wand, sharpen)

    def crop(self, width, height, x, y):
        magic.MagickCropImage(self.wand, width, height, x, y)


    def equalize(self):
        pass

    def cycleColormap(self, displace):
        magic.CycleColormapImage(self.wand, displace)

    def edge(self, radius):
        magic.MagickEdgeImage(self.wand, radius) 

    def emboss(self, radius, sigma):
        magic.MagickEmbossImage(self.wand, radius, sigma)

    def enhance(self):
        magic.MagickEnhanceImage(self.wand)

    def thumbnail(self, width, height):
        self.resize(width, height)

    def _iterate(self):
        magic.MagickResetIterator(self.wand)
        yield magic.MagickNextImage(self.wand)

    def flip(self, x_axis=False, y_axis=False):
        if x_axis == True:
            magic.MagickFlipImage(self.wand)
        if y_axis == True:
            magic.MagickFlopImage(self.wand)

    
    def __del__(self):
        self.wand = magic.DestroyMagickWand(self.wand)




        


if  __name__ == '__main__':
    a = Image("/home/ss/photos/sample.jpg")
    wand = Wand()
    wand.add(a)
    #wand.edge(3)
    #for i in range(10):
    #    wand.cycleColormap()
    #wand.contrast(0)
    #wand.crop(40, 40, 40, 40)
    #wand.resize(40, 40)
    wand.flip(x_axis=True, y_axis=True)
    a.write("/home/ss/photos/test.jpg")
